/**
 * 连接状态工具
 * 提供设备连接状态管理和模拟功能
 */

const logger = require('./logger').logger;
const envDetector = require('./env-detector');

// 蓝牙状态代码
const BLUETOOTH_STATUS = {
  DISCONNECTED: '00', // 未连接
  CONNECTED: '01',   // 已连接
  CONNECTING: '04',  // 连接中
  ERROR: '05'        // 连接错误
};

// WiFi状态代码
const WIFI_STATUS = {
  DISCONNECTED: '02', // 未连接
  CONNECTED: '03',   // 已连接
  CONNECTING: '06',  // 连接中
  ERROR: '07'        // 连接错误
};

// 设备连接状态缓存
const deviceStatusCache = new Map();

// 模拟状态生成函数
function mockConnectionStatus(deviceId) {
  // 如果设备ID不存在，返回默认状态
  if (!deviceId) {
    return {
      bluetoothStatus: BLUETOOTH_STATUS.DISCONNECTED,
      wifiStatus: WIFI_STATUS.DISCONNECTED
    };
  }
  
  // 如果缓存中没有该设备状态，创建随机状态
  if (!deviceStatusCache.has(deviceId)) {
    // 生成随机状态
    const randomStatus = generateRandomStatus();
    deviceStatusCache.set(deviceId, {
      bluetoothStatus: randomStatus.bluetoothStatus,
      wifiStatus: randomStatus.wifiStatus,
      lastUpdate: Date.now()
    });
  }
  
  // 获取缓存状态
  const cachedStatus = deviceStatusCache.get(deviceId);
  
  // 如果已经过去超过30秒，随机变化状态
  const now = Date.now();
  if (now - cachedStatus.lastUpdate > 30000) {
    // 模拟状态变化
    const newStatus = simulateStatusChange(cachedStatus);
    
    // 更新缓存
    cachedStatus.bluetoothStatus = newStatus.bluetoothStatus;
    cachedStatus.wifiStatus = newStatus.wifiStatus;
    cachedStatus.lastUpdate = now;
    
    logger.debug(`模拟设备[${deviceId}]连接状态变化`, newStatus);
  }
  
  return {
    bluetoothStatus: cachedStatus.bluetoothStatus,
    wifiStatus: cachedStatus.wifiStatus
  };
}

/**
 * 生成随机连接状态
 * @returns {Object} 随机状态对象
 */
function generateRandomStatus() {
  // 随机选择一种连接模式
  const connectionMode = Math.random() < 0.7 ? 'bluetooth' : 'wifi';
  
  let bluetoothStatus, wifiStatus;
  
  if (connectionMode === 'bluetooth') {
    // 70%概率连接成功，20%概率连接中，10%概率连接错误
    const rand = Math.random();
    if (rand < 0.7) {
      bluetoothStatus = BLUETOOTH_STATUS.CONNECTED;
    } else if (rand < 0.9) {
      bluetoothStatus = BLUETOOTH_STATUS.CONNECTING;
    } else {
      bluetoothStatus = BLUETOOTH_STATUS.ERROR;
    }
    
    // WiFi大概率未连接
    wifiStatus = Math.random() < 0.9 
      ? WIFI_STATUS.DISCONNECTED 
      : WIFI_STATUS.CONNECTING;
  } else {
    // WiFi模式
    // 70%概率连接成功，20%概率连接中，10%概率连接错误
    const rand = Math.random();
    if (rand < 0.7) {
      wifiStatus = WIFI_STATUS.CONNECTED;
    } else if (rand < 0.9) {
      wifiStatus = WIFI_STATUS.CONNECTING;
    } else {
      wifiStatus = WIFI_STATUS.ERROR;
    }
    
    // 蓝牙大概率未连接
    bluetoothStatus = Math.random() < 0.9 
      ? BLUETOOTH_STATUS.DISCONNECTED 
      : BLUETOOTH_STATUS.CONNECTING;
  }
  
  return { bluetoothStatus, wifiStatus };
}

/**
 * 模拟状态变化
 * @param {Object} currentStatus 当前状态
 * @returns {Object} 新状态
 */
function simulateStatusChange(currentStatus) {
  const { bluetoothStatus, wifiStatus } = currentStatus;
  let newBluetoothStatus = bluetoothStatus;
  let newWifiStatus = wifiStatus;
  
  // 蓝牙状态变化
  const bleRand = Math.random();
  if (bluetoothStatus === BLUETOOTH_STATUS.CONNECTED) {
    // 连接状态有10%概率断开，5%概率出错
    if (bleRand < 0.1) {
      newBluetoothStatus = BLUETOOTH_STATUS.DISCONNECTED;
    } else if (bleRand < 0.15) {
      newBluetoothStatus = BLUETOOTH_STATUS.ERROR;
    }
  } else if (bluetoothStatus === BLUETOOTH_STATUS.DISCONNECTED) {
    // 未连接状态有15%概率连接，10%概率连接中
    if (bleRand < 0.15) {
      newBluetoothStatus = BLUETOOTH_STATUS.CONNECTED;
    } else if (bleRand < 0.25) {
      newBluetoothStatus = BLUETOOTH_STATUS.CONNECTING;
    }
  } else if (bluetoothStatus === BLUETOOTH_STATUS.CONNECTING) {
    // 连接中状态有60%概率连接成功，20%概率失败，20%概率继续连接中
    if (bleRand < 0.6) {
      newBluetoothStatus = BLUETOOTH_STATUS.CONNECTED;
    } else if (bleRand < 0.8) {
      newBluetoothStatus = BLUETOOTH_STATUS.DISCONNECTED;
    }
  } else if (bluetoothStatus === BLUETOOTH_STATUS.ERROR) {
    // 错误状态有70%概率变为未连接，30%概率继续错误
    if (bleRand < 0.7) {
      newBluetoothStatus = BLUETOOTH_STATUS.DISCONNECTED;
    }
  }
  
  // WiFi状态变化
  const wifiRand = Math.random();
  if (wifiStatus === WIFI_STATUS.CONNECTED) {
    // 连接状态有10%概率断开，5%概率出错
    if (wifiRand < 0.1) {
      newWifiStatus = WIFI_STATUS.DISCONNECTED;
    } else if (wifiRand < 0.15) {
      newWifiStatus = WIFI_STATUS.ERROR;
    }
  } else if (wifiStatus === WIFI_STATUS.DISCONNECTED) {
    // 未连接状态有15%概率连接，10%概率连接中
    if (wifiRand < 0.15) {
      newWifiStatus = WIFI_STATUS.CONNECTED;
    } else if (wifiRand < 0.25) {
      newWifiStatus = WIFI_STATUS.CONNECTING;
    }
  } else if (wifiStatus === WIFI_STATUS.CONNECTING) {
    // 连接中状态有60%概率连接成功，20%概率失败，20%概率继续连接中
    if (wifiRand < 0.6) {
      newWifiStatus = WIFI_STATUS.CONNECTED;
    } else if (wifiRand < 0.8) {
      newWifiStatus = WIFI_STATUS.DISCONNECTED;
    }
  } else if (wifiStatus === WIFI_STATUS.ERROR) {
    // 错误状态有70%概率变为未连接，30%概率继续错误
    if (wifiRand < 0.7) {
      newWifiStatus = WIFI_STATUS.DISCONNECTED;
    }
  }
  
  return { bluetoothStatus: newBluetoothStatus, wifiStatus: newWifiStatus };
}

/**
 * 获取设备连接状态
 * @param {string} deviceId 设备ID
 * @param {Object} services 服务对象，包含bluetoothService和wifiService
 * @returns {Object} 连接状态对象
 */
function getDeviceConnectionStatus(deviceId, services = {}) {
  // 如果在开发者工具中，使用模拟状态
  if (envDetector.isDevTools()) {
    return mockConnectionStatus(deviceId);
  }
  if(deviceId!="111"){
return;//TODO 
  }
  
  
  // 获取服务
  const { bluetoothService, wifiService } = services;
  
  // 默认状态
  let bluetoothStatus = BLUETOOTH_STATUS.DISCONNECTED;
  let wifiStatus = WIFI_STATUS.DISCONNECTED;
  
  try {
    // 获取蓝牙连接状态
    if (bluetoothService) {
      const bleState = bluetoothService.getConnectionState(deviceId);
      
      if (bleState === 'connected') {
        bluetoothStatus = BLUETOOTH_STATUS.CONNECTED;
      } else if (bleState === 'connecting') {
        bluetoothStatus = BLUETOOTH_STATUS.CONNECTING;
      } else if (bleState === 'error') {
        bluetoothStatus = BLUETOOTH_STATUS.ERROR;
      }
    }
    
    // 获取WiFi连接状态
    if (wifiService) {
      const wifiState = wifiService.getConnectionState(deviceId);
      
      if (wifiState === 'connected') {
        wifiStatus = WIFI_STATUS.CONNECTED;
      } else if (wifiState === 'connecting') {
        wifiStatus = WIFI_STATUS.CONNECTING;
      } else if (wifiState === 'error') {
        wifiStatus = WIFI_STATUS.ERROR;
      }
    }
  } catch (e) {
    logger.error(`获取设备[${deviceId}]连接状态失败`, e);
  }
  
  return { bluetoothStatus, wifiStatus };
}

/**
 * 清除设备状态缓存
 * @param {string} deviceId 设备ID，不提供则清除所有缓存
 */
function clearStatusCache(deviceId) {
  if (deviceId) {
    deviceStatusCache.delete(deviceId);
  } else {
    deviceStatusCache.clear();
  }
}

/**
 * 重置设备状态为断开连接状态
 * @param {string} deviceId 设备ID
 */
function resetDeviceStatus(deviceId) {
  if (!deviceId) return;
  
  deviceStatusCache.set(deviceId, {
    bluetoothStatus: BLUETOOTH_STATUS.DISCONNECTED,
    wifiStatus: WIFI_STATUS.DISCONNECTED,
    lastUpdate: Date.now()
  });
}

// 导出状态码常量
module.exports = {
  BLUETOOTH_STATUS,
  WIFI_STATUS,
  mockConnectionStatus,
  getDeviceConnectionStatus,
  clearStatusCache,
  resetDeviceStatus
}; 